const { baseUrl, tokenKey } = require("/config");
const { Gender } = require("/constants/user");
const { request } = require("/utils");
const app = getApp();

Page({
    data: {
        userInfo: null,
        infoList: [{
                key: '用户名',
                value: null,
                input: { field: 'username', label: '用户名' }
            },
            {
                key: '性别',
                value: null,
                picker: {
                    title: '请选择性别',
                    optionsOne: ['保密', '男', '女'],
                    selectedOneIndex: 0,
                    success({ selectedOneIndex: gender }) {
                        if (gender === '') return;
                        if (gender === app.globalData.userInfo.gender) return my.showToast({ content: '性别未修改' });
                        const pages = getCurrentPages();
                        const that = pages[pages.length - 1];
                        that.updateUser({ gender });
                    }
                }
            },
            {
                key: '城市',
                value: null,
                regionPicker: true
            },
            {
                key: '邮箱',
                value: null,
                input: { field: 'email', label: '邮箱' }
            },
        ]
    },
    onLoad() {
        this.initData();
    },
    async initData(get) {
        if (get) await app.getUserInfo();
        const { userInfo } = app.globalData;
        const infoList = this.data.infoList.map(item => {
            const { key } = item;
            const { username, gender, province, city, area, email } = userInfo;
            if (key === '用户名') {
                item.value = username;
            }
            if (key === '性别') {
                item.value = gender ? Gender[gender] : null;
                item.picker.selectedOneIndex = gender;
            }
            if (key === '城市') {
                item.value = [province, city, area].filter(item => item).join('-');
            }
            if (key === '邮箱') {
                item.value = email;
            }
            return item;
        });
        this.setData({ userInfo, infoList });
    },
    openAlbum() {
        my.chooseImage({
            sourceType: 'album',
            success: async (imgRes) => {
                const { apFilePaths } = imgRes;
                const tokenData = my.getStorageSync({ key: tokenKey }).data;
                const token = tokenData ? tokenData.token : null;
                my.uploadFile({
                    url: baseUrl + '/miniapp/user/updateAvatar',
                    fileType: 'image',
                    headers: {
                        [tokenKey]: `Bearer ${token}`
                    },
                    filePath: apFilePaths[0],
                    name: 'file',
                    success: ({ data }) => {
                        const { code } = JSON.parse(data);
                        if (code === 200) {
                            my.showToast({
                                type: 'success',
                                content: '上传成功'
                            })
                            this.initData(true);
                        }
                    }
                })
            }
        })
    },
    events: {
        onBack() {
            const pages = getCurrentPages();
            pages[pages.length - 2].getUserInfo();
        }
    },
    tapInfoItem(e) {
        const { index } = e.target.dataset;
        const { picker, regionPicker, input, value } = this.data.infoList[index];
        if (picker) {
            my.optionsSelect(picker);
        }
        if (regionPicker) {
            my.regionPicker({
                title: '请选择城市',
                success: ({ data, code }) => {
                    console.log({ data, code });
                    const [province, city, area] = data;
                    this.updateUser({ province, city, area });
                }
            })
        }
        if (input) {
            my.navigateTo({ url: `/pages/userInfoModifyForm/userInfoModifyForm?field=${input.field}&label=${input.label}&value=${value}` });
        }
    },
    async updateUser(info) {
        my.showLoading({ content: '修改中' });
        try {
            const { code } = await request.post('/miniapp/user/updateUser', info);
            if (code === 200) await this.initData(true);
            my.hideLoading();
            my.showToast({ type: 'success', content: '修改成功' });
        } catch (e) {
            my.hideLoading();
        }
    }
});